<template>
  <el-card class="box-card">
    <!-- {{ $store.state.routerLimits }} -->
    <div slot="header" class="clearfix">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <!-- <el-form-item label="使用人">
          <el-input v-model="formInline.name" placeholder="请输入使用人账号"></el-input>
        </el-form-item>
        <el-form-item label="使用人联系方式">
          <el-input v-model="formInline.name" placeholder="请输入使用人联系方式"></el-input>
        </el-form-item>
        <el-form-item label="角色" class="movement">
          <el-select v-model="formInline.status" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item> -->
        <!-- <el-form-item>
          <el-button type="primary" @click="handleReset">重置</el-button>
        </el-form-item> -->
        <!-- <el-form-item> -->
        <!-- <el-button type="primary" @click="handleAdd">新增</el-button> -->
        <!-- </el-form-item> -->
        <!-- <el-form-item>
          <el-button type="primary" @click="manage">{{ dialogVisible1 ? '取消' : '管理' }}</el-button>
        </el-form-item> -->
      </el-form>
    </div>
    <div class="text item">
      <!-- <el-tree :data="treeList" :props="defaultProps" @node-click="handleNodeClick" node-key="id"
        :expand-on-click-node="false" :default-expanded-keys="[0]">
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }} </span>
          <span v-if="dialogVisible1">
            <el-button type="text" size="mini" @click="() => edit(node, data)">
              编辑
            </el-button>
            <el-button type="text" size="mini" @click="() => append(data)">
              添加
            </el-button>
            <el-button type="text" size="mini" @click="() => remove(node, data)">
              删除
            </el-button>

          </span>
        </span>
      </el-tree> -->

      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        :default-expand-all="false"
        max-height="600"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="id" label="id" width="180"> </el-table-column>
        <el-table-column prop="name" label="菜单名称" width="180">
        </el-table-column>
        <el-table-column prop="url_name" label="路由名称"> </el-table-column>
        <el-table-column prop="url" label="跳转地址"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="edit(scope.row)">
              编辑
            </el-button>
            <el-button type="text" size="mini" @click="append(scope.row)">
              添加
            </el-button>
            <el-button type="text" size="mini" @click="remove(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
      :title="titleText"
    >
      <el-form
        :model="formLabelAlign"
        label-width="85px"
        ref="form"
        :rules="rules"
      >
        <div class="oneLine">
          <el-form-item label="上级菜单" prop="name">
            <el-cascader
              :options="tableData"
              :props="{
                label: 'name',
                value: 'id',
                checkStrictly: true,
                emitPath: false,
              }"
              @change="handleChangeType"
              :value="formLabelAlign.id"
              clearable
            ></el-cascader>
          </el-form-item>
        </div>
        <div class="oneLine">
          <el-form-item label="菜单名称" prop="name">
            <el-input
              v-model="formLabelAlign.name"
              placeholder="请输入项目名称"
            ></el-input>
          </el-form-item>
        </div>
        <div class="oneLine">
          <el-form-item label="跳转地址" prop="name">
            <el-input
              v-model="formLabelAlign.url"
              placeholder="请输入跳转地址"
            ></el-input>
          </el-form-item>
        </div>
        <div class="oneLine">
          <el-form-item label="路由名称">
            <el-input
              v-model="formLabelAlign.url_name"
              placeholder="请输入路由名称"
            ></el-input>
          </el-form-item>
        </div>
        <div class="oneLine">
          <el-form-item label="排序">
            <el-input
            type="number"
              v-model="formLabelAlign.sort"
              placeholder="请输入排序"
            ></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div class="btnBox">
        <el-button
          type="primary"
          dialogVisible
          class="confirm"
          @click="handleClose()"
          >返 回</el-button
        >
        <el-button type="primary" dialogVisible class="confirm" @click="save"
          >确 认</el-button
        >
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { menuList, addMenu, editMenu } from "../../../utils/api";
import { addKXXM, editKXXM, delKXXM } from "../../../utils/main";
export default {
  data() {
    return {
      options: [
        {
          value: "1",
          label: "是",
        },
        {
          value: "2",
          label: "否",
        },
      ],
      formLabelAlign: {},
      fromLabelNode: {},
      token: sessionStorage.getItem("token"),
      dialogVisible: false,
      dialogVisible1: false,
      formInline: {
        status: "",
        name: "",
      },
      tableData: [],
      parameter: {
        common: "",
      },
      name: "",
      status: "",
      type: 2,
      titleText: "",
      parent_id: "0",
      status: "",
      value: "",
      rules: {
        name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
        url: [{ required: true, message: "请输入跳转地址", trigger: "blur" }],
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
      },
      treeList: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      id: 0,
      pid: 0,
      is_delList: [],
    };
  },
  methods: {
    edit(data) {
      console.log(data);
      this.dialogVisible = true;
      this.titleText = "编辑";
      this.formLabelAlign = JSON.parse(JSON.stringify(data));
    },
    handleChangeType(e) {
      console.log(e);
      // this.editDetail.brand_id = "";
      // this.category_id = this.editDetail.category_ids;
    },
    append(data) {
      this.dialogVisible = true;
      this.titleText = "添加";
      console.log(data);
      this.formLabelAlign.id = data.id;
      this.formLabelAlign.pid = data.pid;
      return;
      const newChild = { id: this.id++, label: "testtest", children: [] };
      if (!data.children) {
        this.$set(data, "children", []);
      }
      data.children.push(newChild);
    },
    remove(data) {
      // const parent = node.parent;
      // const children = parent.data.children || parent.data;
      // const index = children.findIndex(d => d.id === data.id);
      // children.splice(index, 1);
      this.$confirm("此操作将永久删除该菜单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(data);
          this.editMenu(
            2,
            this.token,
            data.pid,
            data.name,
            data.url,
            data.url_name,
            1,
            data.id
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleNodeClick(data) {
      // console.log(data);
    },
    //查询
    onSubmit() {
      // this.opinionsS();
      this.name = this.formInline.name;
      this.status = this.formInline.status;
      this.getList();
    },
    handleReset() {
      this.name = "";
      this.status = "";
      this.formInline.name = "";
      this.formInline.status = "";
      this.getList();
    },
    //关闭
    handleClose(done) {
      this.dialogVisible = false;
      this.formLabelAlign = {};
      this.fromLabelNode = {};
      this.$refs.form.resetFields();
    },
    manage() {
      this.dialogVisible1 = !this.dialogVisible1;
    },
    //确定添加
    save() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.titleText == "编辑") {
            //保存
            console.log("保存");
            this.editMenu(
              1,
              this.token,
              this.formLabelAlign.pid,
              this.formLabelAlign.name,
              this.formLabelAlign.url,
              this.formLabelAlign.url_name,
              this.formLabelAlign.sort,
              1,
              this.formLabelAlign.id
            );
            this.handleClose();
          } else {
            //新增
            console.log("新增");
            addMenu(
              this.token,
              this.formLabelAlign.id,
              this.formLabelAlign.name,
              this.formLabelAlign.url,
              this.formLabelAlign.url_name,
              this.formLabelAlign.sort
            ).then((res) => {
              console.log(res);
              if (res.data.status) {
                this.handleClose();
                this.getList();
              } else {
                this.$message.error(res.data.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    // 接口-==--=============================================
    editMenu(type, token, pid, name, url, url_name, is_del, id) {
      editMenu(type, token, pid, name, url, url_name, is_del, id).then(
        (res) => {
          if (res.data.status) {
            if (type == 1) {
              this.$message({
                type: "success",
                message: "保存成功!",
              });
            } else {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            }
          }
          this.getList();
        }
      );
    },
    // 新增
    handleRemove() {},

    // 获取列表
    async getList() {
      this.loading = true;
      let res = await menuList(this.token);
      if (res.data.status) {
        // console.log(this.listToTree(res.data.data || []),'asd');
        this.id = res.data.data[res.data.data.length - 1].id;
        // this.treeList = this.listToTree(res.data.data || [])
        this.tableData = this.listToTree(res.data.data || []);
        //id_del     0 展示  1 不展示
      } else {
        if (res.data.msg == "token失效,请重新进行登录") {
          this.$router.push("/login");
        }
        if (res.data.msg == "此账号没有权限") {
          this.$message.error(res.data.msg);
          this.loading = false;
        }
        let timer = setTimeout(() => {
          this.$message.error(res.data.msg);
        }, 5000);
      }
    },
    listToTree(data) {
      // * 先生成parent建立父子关系
      const obj = {};
      data.forEach((item) => {
        obj[item.id] = item;
      });
      // * obj -> {1001: {id: 1001, parentId: 0, name: 'AA'}, 1002: {...}}
      console.log(obj, "obj");
      const parentList = [];
      data.forEach((item) => {
        const parent = obj[item.pid];
        if (parent) {
          // * 当前项有父节点
          parent.children = parent.children || [];
          parent.children.push(item);
        } else {
          // * 当前项没有父节点 -> 顶层
          parentList.push(item);
        }
      });
      console.log(parentList);
      const list = [];
      list.unshift({
        ctime: null,
        id: "0",
        is_del: 0,
        name: "顶级分类",
        pid: 0,
        sort: null,
        url: null,
        url_name: null,
        children: parentList,
      });
      return list;
    },
  },
  mounted() {
    // this.opinionsS();
    this.getList();

    let list = [
      {
        createTime: 1715579620000,
        creator: "1",
        deleted: false,
        formula: "",
        indicatorIds: "[null]",
        indicatorUnit: "",
        indicatorVal: 0,
        labelId: 45,
        level: "一级指标",
        name: "研发投入强度",
        relatedDesc: "研发投入强度=",
        relatedIndicator: "",
        remarks: "",
        type: "项目",
        updateTime: 1715579620000,
        updater: "1",
      },
      {
        createTime: 1715579620000,
        creator: "1",
        deleted: false,
        formula: "基建+技改（含零小技改）+信息化+前期费+股权",
        indicatorIds: "[50, null, 52, 53, 54]",
        indicatorUnit: "",
        indicatorVal: 0,
        labelId: 46,
        level: "一级指标",
        name: "投资",
        relatedDesc: "投资=基建+技改（含零小技改）+信息化+前期费+股权",
        relatedIndicator: "基建、技改（含零小技改）、信息化、前期费、股权",
        remarks: "",
        type: "项目",
        updateTime: 1715579620000,
        updater: "1",
      },
    ];

    // 一般 pid 就是 parentId，指的是父级 id，这里默认是 pid
    // childName 在大多数表格，多级嵌套等组件里通常都是用 children 命名，这里默认是 children
    let result = []; // 初始化
    for (let i = 0; i < list.length; i++) {
      result.push({ lable: list[i].type, child: [] });
    }

    let map = new Map();
    let array = [];

    var result1 = {};
    for (var i = 0; i < result.length; i++) {
      result1[result[i]["lable"]] = result[i];
    }
    console.log(result1, "ssssssssssss");
    for (let i = 0; i < list.length; i++) {
      // result1.push({lable:list[i].type})
      result1[list[i].type].child.push({ lable: list[i].name });
    }
    console.log(result1, "2222222222222");
    // // 将数据以对象的格式先存起来
    // list.forEach(item => {
    //   obj[item.labelId] = item
    // })
    // console.log(obj);
    // for (let i = 0; i < list.length; i++) {
    //   let item = list[i]
    //   // 这里去 obj 里找，如果没有找到那就是 undefined，说明这个当前 item 是根节点
    //   let parent = obj[item['type']]
    //   console.log(parent,'parent',item['type']);
    //   if (parent) {
    //     (parent['child'] || (parent['child'] = [])).push(item)
    //   } else {
    //     result.push(item)
    //   }
    //   console.log(item);
    // }

    // console.log(result,'result');
  },
};
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  max-height: 70vh;
  overflow-y: scroll;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}

.divFlex {
  display: flex;
  align-items: center;
}

.oneLine {
  display: flex;
  justify-content: space-between;
  margin-bottom: 14px;
}

.addP {
  font-size: 22px;
  text-align: center;
  margin-bottom: 10px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.btnBox {
  display: flex;
  justify-content: center;
}
</style>